package com.captain.special.链表;

import com.captain.leetcode.链表.ListNode;

import java.util.List;

/**
 * Des:
 *
 * @author XL
 * @Date 2022/3/22 12:53
 */
public class 旋转链表61 {
    public static void main(String[] args) {
        new 旋转链表61().rotateRight(ListNode.getInstance(), 5);

    }

    public ListNode rotateRight(ListNode head, int k) {
        if (head == null || head.next == null || k == 0) return head;
        ListNode dummy = new ListNode(-1, head);
        //操作链表 -112345 2    45 123
        ListNode cur = dummy;
        ListNode lengthNode = dummy.next;
        int len = 0;
        while (lengthNode != null) {
            len++;
            lengthNode = lengthNode.next;
        }
        k %= len;
        if (k == 0) return head;
        int index = len - k;
        for (int i = 0; i < index; i++) {
            cur = cur.next;
        }
        // 3 4
        ListNode rotateNode = cur.next;
        cur.next = null;
        ListNode pre = dummy.next;
        //-1 3 4 1 2
        dummy.next = rotateNode;
        ListNode curRotateNode = rotateNode;
        while (curRotateNode.next != null) {
            curRotateNode = curRotateNode.next;
        }
        curRotateNode.next = pre;
        return dummy.next;
    }
}
